const fs = require('fs');
const path = require('path');
const Kuroshiro = require('kuroshiro').default;
const KuromojiAnalyzer = require('kuroshiro-analyzer-kuromoji');
const Kuromoji = require('kuromoji');

// 指定目录
const targetDirectory = 'C:/E/temp/pic/lrc/';

/** 日语句字划分分词 */
function processJpFenci(inputFile, outputFile) {
    // 创建 Kuromoji 分词器
    Kuromoji.builder({ dicPath: './node_modules/kuromoji/dict' }).build((err, tokenizer) => {
        if (err) {
            console.error(err);
            return;
        }

        // 读取包含日文文本的txt文件
        fs.readFile(inputFile, 'utf8', (err, data) => {
            if (err) {
                console.error(err);
                return;
            }

            // 按句子分割文本（简单按句号分割，实际可能更复杂）
            const sentences = data.split('。');

            let result = '';
            sentences.forEach((sentence) => {
                if (sentence.trim() !== '') {
                    const tokens = tokenizer.tokenize(sentence);
                    const tokenText = tokens.map((token) => token.surface).join(' ');
                    result += tokenText + '\n';
                }
            });

            // 将结果写入新的文本文件
            fs.writeFile(outputFile, result, 'utf8', (err) => {
                if (err) {
                    console.error(err);
                    return;
                }
                console.log('分词结果已成功写入output.txt');
            });
        });
    });
}


// 初始化 Kuroshiro
const kuroshiro = new Kuroshiro();
async function initKuroshiro() {
    const analyzer = new KuromojiAnalyzer();
    await kuroshiro.init(analyzer);
}

// 遍历指定目录下的所有 .lrc 文件
function traverseLrcFiles() {
    fs.readdir(targetDirectory, (err, files) => {
        if (err) {
            console.error('读取目录时出错:', err);
            return;
        }
        files.forEach(file => {
            if (path.extname(file) === '.lrc') {
                const filePath = path.join(targetDirectory, file);
                convertLrcFile(filePath);
            }
        });
    });
}

// 把文件(content.txt)中的日文句子转为分词、平假名、罗马音
async function convertTxtFile(filePath){
    const data = fs.readFileSync(filePath, 'utf8');
    const lines = data.replace('\n','。').replace('？','。').replace('.','。').split('。');
    const convertLines = ['# translate\n'];
    const kanji_list = [];
    let no = 1;
    for (let line of lines){
        // console.log(line)
        let d = await packDictForTransJp(line.trim());
        convertLines.push([`${no}. ${d['orig']}`]);
        convertLines.push([`   - ${d['fenci']}`]);
        convertLines.push([`   - ${d['hira']}`]);
        convertLines.push([`   - ${d['roma']}`]);
        convertLines.push([`   - ${d['okur']}`]);
        convertLines.push(['']);
        kanji_list.push(d['kanji']);
        no += 1;
    }
    convertLines.push(`   > ${kanji_list.join(',')}\n`);
    // console.log(convertLines);
    fs.writeFileSync('./contentConvert.md', convertLines.join('\n'), 'utf8');
}

// 转换单个 LRC 文件
async function convertLrcFile(filePath) {
    try {
        const data = fs.readFileSync(filePath, 'utf8');
        const lines = data.split('\n');
        const kanji_list = []
        const convertedLines = [];
        const convertedMarkdownLines = ['## '+path.basename(filePath),packMarkdownTableHead('timestamps','orig','fenci','hira','roma')]; // markdown 文档标题和table表头
        for (let line of lines) {
            if (!Kuroshiro.Util.hasJapanese(line)){
                continue;
            }
            line = line.replace('\r','');
            let divide_index = line.indexOf(']')+1;
            let timestamps =  line.slice(0,divide_index);
            let no_timestamps = line.slice(divide_index);
            let d = await packDictForTransJp(no_timestamps);
            // console.log(d);
            // 添加特殊标记，这里以方括号为例
            // const formattedLine = `[${convertedLine}]`; 
            convertedLines.push(`${timestamps}${d['fenci']}`);
            // convertedLines.push(`${timestamps}${d['okur']}`);
            convertedLines.push(`${timestamps}${d['hira']}`);
            // convertedLines.push(`${timestamps}${d['roma']}`);

            convertedMarkdownLines.push(packMarkdownTableContent(timestamps,d['orig'],d['fenci'],d['hira'],d['roma']));
            kanji_list.push(...d['kanji'])

        }
        // 搜集日文里的汉字 记录在txt文本里 后续处理
        const outputKanjiFile = path.join(targetDirectory, path.basename(filePath, '.lrc') + '_kanji.txt');
        fs.writeFileSync(outputKanjiFile, kanji_list.join(','), 'utf8');

        const outputMarkdownFilePath = path.join(targetDirectory, path.basename(filePath, '.lrc') + '.md');
        fs.writeFileSync(outputMarkdownFilePath, convertedMarkdownLines.join('\n'), 'utf8');

        const convertedContent = convertedLines.join('\n');
        const outputFilePath = path.join(targetDirectory, path.basename(filePath, '.lrc') + '_converted.lrc');
        fs.writeFileSync(outputFilePath, convertedContent, 'utf8');
        console.log(`转换完成: ${filePath} -> ${outputFilePath}`);
    } catch (error) {
        console.error(`处理文件 ${filePath} 时出错:`, error);
    }
}

// 主函数
async function main() {
    await initKuroshiro();
    traverseLrcFiles();
    // convertTxtFile('./content.txt');
}

main();
const match_ruby = new RegExp('<ruby>(.*?)<rp>\\(</rp><rt>(.*?)</rt><rp>\\)</rp></ruby>','g');
/** 把日文转换后的结果封装成dict字典 */
async function packDictForTransJp(sentence) {
    let d = {}
    let kanji = [] // 日文汉字集合
    d['orig'] = sentence;
    d['hira'] = await kuroshiro.convert(sentence, { to: 'hiragana', mode: 'spaced' });
    d['okur'] = await kuroshiro.convert(sentence, { to: 'hiragana', mode:'okurigana'});
    d['furigana'] = await kuroshiro.convert(sentence,{ to: 'hiragana', mode:'furigana'});
    // console.log(d['okur']);
    d_fenci = d['hira'];
    for (let t of d['furigana'].matchAll(match_ruby)){
        // console.log(t);
        d_fenci = d_fenci.replace(t[2],t[1]);
        // if (Kuroshiro.Util.hasJapanese(t[1])){
        //     kanji.push(t[1]);
        // }
        kanji.push(t[1]);
    }
    d['fenci'] = d_fenci
    d['roma'] = await kuroshiro.convert(sentence, { to: 'romaji', mode: 'spaced' });
    d['kanji'] = kanji
    return d;
}
/** 拼接markdown table表头 */
function packMarkdownTableHead(...args) {
    let h = '|';
    let d = '|';
    for (let i of args) {
        h += `${i}|`;
        d += `---|`;
    }
    return `${h}\n${d}`;
}
/** 拼接markdown table内容 */
function packMarkdownTableContent(...args) {
    let c = '|'
    for (let i of args) {
        c += `${i}|`;
    }
    return c;
}
